//
//  NIMSessionListViewController.m
//  NIMKit
//
//  Created by NetEase.
//  Copyright (c) 2015年 NetEase. All rights reserved.
//

#import "NIMSessionListViewController.h"
#import "NIMSessionViewController.h"
#import "NIMSessionListCell.h"
#import "UIView+NIM.h"
#import "NIMAvatarImageView.h"
#import "NIMKitUtil.h"
#import "NIMKit.h"
#import "SheYangBigData-Swift.h"

@interface NIMSessionListViewController ()

@property(nonatomic, strong) UIButton *aboveBt;
@property(nonatomic, strong) NSMutableArray<NIMTeam *> * teams;
@property(nonatomic, assign) NSInteger cellCount;
@property(nonatomic, assign) NSInteger requestCount;
@property(nonatomic, assign) CGFloat pushTipHeight;

@end

static NSString *const NIMRecentSessionTopMark = @"NIMSRecentSessionTopMark";

@implementation NIMSessionListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)dealloc{
    [[NIMSDK sharedSDK].conversationManager removeDelegate:self];
    [[NIMSDK sharedSDK].loginManager removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    _requestCount = 20;
    self.view.backgroundColor = NIMKit_UIColorFromRGB(0xf2f2f2);
    
    CGFloat topMargin = 64;
    CGFloat bottomMargin = 49;
    if ([UIScreen mainScreen].bounds.size.height == 812 || [UIScreen mainScreen].bounds.size.height == 896) {
        topMargin = 88;
        bottomMargin = 83;
    }
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topMargin, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - topMargin - bottomMargin) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.tableFooterView  = [[UIView alloc] init];
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = NIMKit_UIColorFromRGB(0xf2f2f2);
    self.tableView.bounces = NO;

    [self changeAccount];

    [[NIMSDK sharedSDK].conversationManager addDelegate:self];
    [[NIMSDK sharedSDK].loginManager addDelegate:self];
    
    extern NSString *const NIMKitTeamInfoHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTeamInfoHasUpdatedNotification:) name:NIMKitTeamInfoHasUpdatedNotification object:nil];
    
    extern NSString *const NIMKitTeamMembersHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTeamMembersHasUpdatedNotification:) name:NIMKitTeamMembersHasUpdatedNotification object:nil];
    
    extern NSString *const NIMKitUserInfoHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoHasUpdatedNotification:) name:NIMKitUserInfoHasUpdatedNotification object:nil];
}

// 切换账号 更新列表
- (void)changeAccount {

    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    if (!self.recentSessions.count)
    {
        _recentSessions = [NSMutableArray array];
    }
    else
    {
        _recentSessions = [self customSortRecents:_recentSessions];
    }
    
    NSMutableArray<NIMTeam *> * allTeams = [[NSMutableArray alloc] init];
    VGIMManager * m = [[VGIMManager alloc] init];
//    NSMutableArray<NSString *> * teamIds = [m getTeamIds];
    // 获取所有teamid对应的MINTeam
//    if (teamIds.count != 0) {
//        for (NIMTeam *team in [[NIMSDK sharedSDK].teamManager.allMyTeams mutableCopy]) {
//            for (NSString *teamId in teamIds) {
//                if ([team.teamId isEqualToString: teamId]) {
//                    [allTeams addObject:team];
//                }
//            }
//        }
//    } else {
        allTeams = [[NIMSDK sharedSDK].teamManager.allMyTeams mutableCopy];
//    }
    
    NSMutableArray<NIMTeam *> * teamsCopy = [allTeams mutableCopy];
    // 如果群组id 在最近会话中的话 只显示最近会话 不显示该群组（防止显示重复）
    for (NIMRecentSession *recentSession in _recentSessions) {
        if (recentSession.session.sessionType == NIMSessionTypeTeam) {
            for (NIMTeam *team in [allTeams mutableCopy]) {
                NSLog(@"team.teamId: %@===recentSession.session.sessionId: %@", team.teamId, recentSession.session.sessionId);
                if ([[NIMSDK sharedSDK].teamManager isMyTeam:team.teamId]) {
                    if ([recentSession.session.sessionId isEqualToString: team.teamId]) {
                        [teamsCopy removeObject:team];
                    }
                }
            }
        }
    }
    
    _teams = teamsCopy;
    _cellCount = self.recentSessions.count + _teams.count;
    if (_cellCount == 0 && _requestCount > 0) {
        _requestCount -= 1;
//        if ([NetConstants.api containsString:@"map8"]) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self changeAccount];
//            });
//        }
    }
    NSLog(@"=========cellcount==========%ld", (long)_cellCount);
    [self refresh];
}

- (void)refresh{
    [self.tableView reloadData];
}

- (CGFloat)tableViewTopMargin {
    CGFloat topMargin = 10.0;
    return topMargin;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_recentSessions.count > indexPath.row) {
        NIMRecentSession *recentSession = self.recentSessions[indexPath.row];
        VGIMOCSessionViewController *vc = [[VGIMOCSessionViewController alloc] initWithSession:recentSession.session compeletionBlock:^{
            [self changeAccount];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        NIMTeam *team = _teams[indexPath.row - _recentSessions.count];
        NIMSession *session = [NIMSession session:team.teamId type: NIMSessionTypeTeam];
        VGIMOCSessionViewController *vc = [[VGIMOCSessionViewController alloc] initWithSession:session compeletionBlock:^{
            [self changeAccount];
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat pushTipHeight = [self calculatePushTipHeight];
//    if (BadgeValueUtils.NOT_DYNAMIC_COUNT != 0) {
//        return 125 - [self tableViewTopMargin] + pushTipHeight;
//    } else {
        return 65 - [self tableViewTopMargin] + pushTipHeight;
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_recentSessions.count > indexPath.row) {
        return YES;
    }
    return NO;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NIMRecentSession *recentSession = weakSelf.recentSessions[indexPath.row];
        [weakSelf onDeleteRecentAtIndexPath:recentSession atIndexPath:indexPath];
        [tableView setEditing:NO animated:YES];
    }];
    
    
    NIMRecentSession *recentSession = weakSelf.recentSessions[indexPath.row];
    BOOL isTop = [weakSelf recentSessionIsMark:recentSession];
    UITableViewRowAction *top = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:isTop?@"取消置顶":@"置顶" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [weakSelf onTopRecentAtIndexPath:recentSession atIndexPath:indexPath isTop:isTop];
        [tableView setEditing:NO animated:YES];
    }];
    
    return @[delete,top];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _cellCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellId = @"cellId";
    NIMSessionListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NIMSessionListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        [cell.avatarImageView addTarget:self action:@selector(onTouchAvatar:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    if (_recentSessions.count > indexPath.row) {
        
        NIMRecentSession *recent = self.recentSessions[indexPath.row];
        cell.nameLabel.text = [self nameForRecentSession:recent];
        [cell.avatarImageView setAvatarBySession:recent.session];
        [cell.nameLabel sizeToFit];
        cell.messageLabel.attributedText  = [self contentForRecentSession:recent];
        [cell.messageLabel sizeToFit];
        cell.timeLabel.text = [self timestampDescriptionForRecentSession:recent];
        [cell.timeLabel sizeToFit];
        
        [cell refresh:recent isLastCell:(indexPath.row == _cellCount - 1) nameTop:17];
        
        if ([self recentSessionIsMark:recent]) {
            cell.backgroundColor = NIMKit_UIColorFromRGB(0xf2f2f2);
            if (indexPath.row == 0) {
                [cell.topLineView setHidden:NO];
            } else {
                [cell.topLineView setHidden:YES];
            }
        } else {
            cell.backgroundColor = [UIColor whiteColor];
            [cell.topLineView setHidden:YES];
        }
    } else {
        NIMTeam *team = _teams[indexPath.row - _recentSessions.count];
        NSString *teamId = team.teamId;
        cell.nameLabel.text = [[NIMSDK sharedSDK].teamManager teamById:teamId].teamName;
        [cell.nameLabel sizeToFit];
        NSURL *url = [NSURL URLWithString:team.avatarUrl];
        NIMKitInfo *info = [[NIMKit sharedKit] infoByTeam:teamId option:nil];
        [cell.avatarImageView nim_setImageWithURL:url placeholderImage:info.avatarImage];
        NIMRecentSession *recentSession = [[NIMRecentSession alloc] init];
        cell.messageLabel.attributedText  = [self contentForRecentSession:recentSession];
        [cell.messageLabel sizeToFit];
        cell.timeLabel.text = @"";
        [cell.timeLabel sizeToFit];
        [cell refresh:recentSession isLastCell:(indexPath.row == _cellCount - 1) nameTop:17];
        
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CGFloat pushTipHeight = [self calculatePushTipHeight];
    CGFloat viewHeight = 0.0;
//    if (BadgeValueUtils.NOT_DYNAMIC_COUNT != 0) {
//        viewHeight = 125 - [self tableViewTopMargin] + pushTipHeight;
//    } else {
        viewHeight = 65 - [self tableViewTopMargin] + pushTipHeight;
//    }
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];

//    ChatInviteFamilyCell *chatCell = [[ChatInviteFamilyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ChatInviteFamilyCell"];
//
//
//    if (pushTipHeight == 45) {
//        view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, viewHeight - 10);
//        [view addSubview:[self setupPushTipTopView]];
//        [view addSubview: [self setupPushTipView]];
//        chatCell.frame = CGRectMake(0, pushTipHeight, [UIScreen mainScreen].bounds.size.width, 65 - [self tableViewTopMargin]);
//    } else {
//        view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, viewHeight);
//        [view addSubview:[self setupPushTipTopView]];
//        chatCell.frame = CGRectMake(0, pushTipHeight, [UIScreen mainScreen].bounds.size.width, 65 - [self tableViewTopMargin]);
//    }
//
//    chatCell.backgroundColor = [UIColor whiteColor];
//    [chatCell updateValueWithCount:BadgeValueUtils.NOT_INVITE_COUNT];
//    [chatCell updateTopGrayHeightWithHeight:0];
//    chatCell.clickClosure = ^{
//        [self headerViewClicked:0];
//    };
//    [view addSubview:chatCell];
    
//    /// 动态消息的cell
//    if (BadgeValueUtils.NOT_DYNAMIC_COUNT != 0) {
//
//        DynamicMsgCell *dynamicCell = [[DynamicMsgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DynamicMsgCell"];
//        dynamicCell.frame = CGRectMake(0, 65 - [self tableViewTopMargin] + pushTipHeight, [UIScreen mainScreen].bounds.size.width, 60);
//
//        CGFloat topMargin = 64;
//        if ([UIScreen mainScreen].bounds.size.height == 812 || [UIScreen mainScreen].bounds.size.height == 896) {
//            topMargin = 78;
//        }
//
//        if (BadgeValueUtils.NOT_DYNAMIC_COUNT < 10) {
//            dynamicCell.redDot.text = [NSString stringWithFormat:@"%ld", (long)BadgeValueUtils.NOT_DYNAMIC_COUNT];
//        } else if (BadgeValueUtils.NOT_DYNAMIC_COUNT <= 99) {
//            [dynamicCell updateRedDotWithWidth:26];
//            dynamicCell.redDot.text = [NSString stringWithFormat:@"%ld", (long)BadgeValueUtils.NOT_DYNAMIC_COUNT];
//        } else {
//            [dynamicCell updateRedDotWithWidth:34];
//            dynamicCell.redDot.text = @"99+";
//        }
//        dynamicCell.clickClosure = ^{
//            [self headerViewClicked:1];
//            BadgeValueUtils.NOT_DYNAMIC_COUNT = 0;
//            [self.tableView reloadData];
//        };
//
//        [view addSubview:dynamicCell];
//    }
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0.01)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

- (void)headerViewClicked:(NSInteger)Index {
    
}

#pragma mark - NIMConversationManagerDelegate
- (void)didAddRecentSession:(NIMRecentSession *)recentSession
           totalUnreadCount:(NSInteger)totalUnreadCount{
    [self.recentSessions addObject:recentSession];
    [self sort];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}


- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount{
//    BadgeValueUtils.NEW_IMMESSAGE_COUNT = totalUnreadCount;
    for (NIMRecentSession *recent in self.recentSessions)
    {
        if ([recentSession.session.sessionId isEqualToString:recent.session.sessionId])
        {
            [self.recentSessions removeObject:recent];
            break;
        }
    }
    NSInteger insert = [self findInsertPlace:recentSession];
    [self.recentSessions insertObject:recentSession atIndex:insert];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)didRemoveRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount
{
    //清理本地数据
    NSInteger index = [self.recentSessions indexOfObject:recentSession];
    [self.recentSessions removeObjectAtIndex:index];
    
    //如果删除本地会话后就不允许漫游当前会话，则需要进行一次删除服务器会话的操作
    if (self.autoRemoveRemoteSession)
    {
        [[NIMSDK sharedSDK].conversationManager deleteRemoteSessions:@[recentSession.session]
                           completion:nil];
    }
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)messagesDeletedInSession:(NIMSession *)session{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)allMessagesDeleted{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (void)allMessagesRead
{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    _recentSessions = [self customSortRecents:_recentSessions];
    [self refresh];
}

- (NSMutableArray *)customSortRecents:(NSMutableArray *)recentSessions
{
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:recentSessions];
    // 冒泡排序
    [array sortUsingComparator:^NSComparisonResult(NIMRecentSession *obj1, NIMRecentSession *obj2) {
        NSInteger score1 = [self recentSessionIsMark:obj1]? 10 : 0;
        NSInteger score2 = [self recentSessionIsMark:obj2]? 10 : 0;
        if (obj1.lastMessage.timestamp > obj2.lastMessage.timestamp)
        {
            score1 += 1;
        }
        else if (obj1.lastMessage.timestamp < obj2.lastMessage.timestamp)
        {
            score2 += 1;
        }
        if (score1 == score2)
        {
            return NSOrderedSame;
        }
        return score1 > score2? NSOrderedAscending : NSOrderedDescending;
    }];
    return array;
}

#pragma mark - NIMLoginManagerDelegate
- (void)onLogin:(NIMLoginStep)step
{
    if (step == NIMLoginStepSyncOK) {
        [self refresh];
    }
}

#pragma mark - Override
- (void)onSelectedAvatar:(NSString *)userId
             atIndexPath:(NSIndexPath *)indexPath{};

- (void)onSelectedRecent:(NIMRecentSession *)recentSession atIndexPath:(NSIndexPath *)indexPath{
    NIMSessionViewController *vc = [[NIMSessionViewController alloc] initWithSession:recentSession.session];
    [self.navigationController pushViewController:vc animated:YES];
}



- (NSString *)nameForRecentSession:(NIMRecentSession *)recent{
    if (recent.session.sessionType == NIMSessionTypeP2P) {
        NSString *name = [NIMKitUtil showNick:recent.session.sessionId inSession:recent.session];
        return name == recent.session.sessionId ? @"" : name;
    }else{
        NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:recent.session.sessionId];
        return team.teamName == recent.session.sessionId ? @"" : team.teamName;
    }
}

- (NSAttributedString *)contentForRecentSession:(NIMRecentSession *)recent{
    NSString *content = [self messageContent:recent.lastMessage];
    return [[NSAttributedString alloc] initWithString:content ?: @"暂无群聊消息"];
}

- (NSString *)timestampDescriptionForRecentSession:(NIMRecentSession *)recent{
    return [NIMKitUtil showTime:recent.lastMessage.timestamp showDetail:NO];
}

#pragma mark - Misc

- (NSInteger)findInsertPlace:(NIMRecentSession *)recentSession{
    __block NSUInteger matchIdx = 0;
    __block BOOL find = NO;
    [self.recentSessions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NIMRecentSession *item = obj;
        if (item.lastMessage.timestamp <= recentSession.lastMessage.timestamp) {
            *stop = YES;
            find  = YES;
            matchIdx = idx;
        }
    }];
    if (find) {
        return matchIdx;
    }else{
        return self.recentSessions.count;
    }
}

- (void)sort{
    [self.recentSessions sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NIMRecentSession *item1 = obj1;
        NIMRecentSession *item2 = obj2;
        if (item1.lastMessage.timestamp < item2.lastMessage.timestamp) {
            return NSOrderedDescending;
        }
        if (item1.lastMessage.timestamp > item2.lastMessage.timestamp) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
}

- (void)onTouchAvatar:(id)sender{
    UIView *view = [sender superview];
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = view.superview;
    }
    UITableViewCell *cell  = (UITableViewCell *)view;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NIMRecentSession *recent = self.recentSessions[indexPath.row];
    [self onSelectedAvatar:recent atIndexPath:indexPath];
}



#pragma mark - Private
- (NSString *)messageContent:(NIMMessage*)lastMessage{
    NSString *text = @"";
    switch (lastMessage.messageType) {
        case NIMMessageTypeText:
            text = lastMessage.text;
            break;
        case NIMMessageTypeAudio:
            text = @"[语音]";
            break;
        case NIMMessageTypeImage:
            text = @"[图片]";
            break;
        case NIMMessageTypeVideo:
            text = @"[视频]";
            break;
        case NIMMessageTypeLocation:
            text = @"[位置]";
            break;
        case NIMMessageTypeNotification:{
            return [self notificationMessageContent:lastMessage];
        }
        case NIMMessageTypeFile:
            text = @"[文件]";
            break;
        case NIMMessageTypeTip:
            text = lastMessage.text;
            break;
        case NIMMessageTypeRobot:
            text = [self robotMessageContent:lastMessage];
            break;
        default:
            text = @"[未知消息]";
    }
    if (lastMessage.session.sessionType == NIMSessionTypeP2P || lastMessage.messageType == NIMMessageTypeTip)
    {
        return text;
    }
    else
    {
        NSString *from = lastMessage.from;
        if (lastMessage.messageType == NIMMessageTypeRobot)
        {
            NIMRobotObject *object = (NIMRobotObject *)lastMessage.messageObject;
            if (object.isFromRobot)
            {
                from = object.robotId;
            }
        }
//        if ([from isEqualToString:UserRepository.instance.getuser.yxYqxImUserInfo.accid]) {
//            return text;
//        } else {
            NSString *nickName = [NIMKitUtil showNick:from inSession:lastMessage.session];

            if ([nickName isEqualToString:from]) {
                nickName = [NIMKitUtil showNick:from inSession:lastMessage.session];
                return nickName.length ? text : @"";
            } else {
                return nickName.length ? [nickName stringByAppendingFormat:@" : %@",text] : @"";
            }
//        }
    }
}

- (NSString *)notificationMessageContent:(NIMMessage *)lastMessage{
    NIMNotificationObject *object = lastMessage.messageObject;
    if (object.notificationType == NIMNotificationTypeNetCall) {
        NIMNetCallNotificationContent *content = (NIMNetCallNotificationContent *)object.content;
        if (content.callType == NIMNetCallTypeAudio) {
            return @"[网络通话]";
        }
        return @"[视频聊天]";
    }
    if (object.notificationType == NIMNotificationTypeTeam) {
        NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:lastMessage.session.sessionId];
        if (team.type == NIMTeamTypeNormal) {
            return @"[讨论组信息更新]";
        }else{
//            return [NIMKitUtil messageTipContent:lastMessage];
            return @"[群信息更新]";
        }
    }
    return @"[未知消息]";
}

- (NSString *)robotMessageContent:(NIMMessage *)lastMessage{
    NIMRobotObject *object = lastMessage.messageObject;
    if (object.isFromRobot)
    {
        return @"[机器人消息]";
    }
    else
    {
        return lastMessage.text;
    }
}


#pragma mark - Notification
- (void)onUserInfoHasUpdatedNotification:(NSNotification *)notification{
    [self refresh];
}

- (void)onTeamInfoHasUpdatedNotification:(NSNotification *)notification{
    [self refresh];
}

- (void)onTeamMembersHasUpdatedNotification:(NSNotification *)notification{
    for (NIMRecentSession *recentSession in [self.recentSessions reverseObjectEnumerator]) {
        NSString *lastTest = [NIMKitUtil messageTipContent:recentSession.lastMessage];
        if ([lastTest containsString:@"解散了"] || [lastTest containsString:@"移出了"] || [lastTest containsString:@"离开了"]) {
            NSLog(@"%@", lastTest);
            [self onDeleteRecentAtIndexPath:recentSession atIndexPath:nil];
        }
    }
    [self changeAccount];
//    [self refresh];
}


- (void)onDeleteRecentAtIndexPath:(NIMRecentSession *)recent atIndexPath:(NSIndexPath *)indexPath
{
    id<NIMConversationManager> manager = [[NIMSDK sharedSDK] conversationManager];
    NIMDeleteMessagesOption *option = [[NIMDeleteMessagesOption alloc] init];
    option.removeTable = YES;
    option.removeSession = YES;
    [manager deleteAllmessagesInSession:recent.session option:option];
    [self changeAccount];
}

- (void)onTopRecentAtIndexPath:(NIMRecentSession *)recent
                   atIndexPath:(NSIndexPath *)indexPath
                         isTop:(BOOL)isTop
{
    if (isTop)
    {
        [self removeRecentSessionMark:recent.session];
    }
    else
    {
        [self addRecentSessionMark:recent.session];
    }
    self.recentSessions = [self customSortRecents:self.recentSessions];
    [self.tableView reloadData];
}

- (void)addRecentSessionMark:(NIMSession *)session
{
    NIMRecentSession *recent = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
    if (recent)
    {
        NSDictionary *localExt = recent.localExt?:@{};
        NSMutableDictionary *dict = [localExt mutableCopy];
        NSString *key = NIMRecentSessionTopMark;
        [dict setObject:@(YES) forKey:key];
        [[NIMSDK sharedSDK].conversationManager updateRecentLocalExt:dict recentSession:recent];
    }
    
    
}

- (void)removeRecentSessionMark:(NIMSession *)session
{
    NIMRecentSession *recent = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
    if (recent) {
        NSMutableDictionary *localExt = [recent.localExt mutableCopy];
        NSString *key = NIMRecentSessionTopMark;
        [localExt removeObjectForKey:key];
        [[NIMSDK sharedSDK].conversationManager updateRecentLocalExt:localExt recentSession:recent];
    }
}

- (BOOL)recentSessionIsMark:(NIMRecentSession *)recent
{
    NSDictionary *localExt = recent.localExt;
    NSString *key = NIMRecentSessionTopMark;
    return [localExt[key] boolValue] == YES;
}

- (UIView *)setupPushTipTopView {
    
    UIView * pushTipTopView = [[UIView alloc] init];
    pushTipTopView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 10);
    pushTipTopView.backgroundColor = [UIColor colorWithHex:0xf2f2f2];
    return pushTipTopView;
}

- (UIView *)setupPushTipView {
    
    UIView * pushTipView = [[UIView alloc] init];
    pushTipView.frame = CGRectMake(0, 10, [UIScreen mainScreen].bounds.size.width, 35);
    pushTipView.backgroundColor = [UIColor colorWithHex:0xfff4dd];
    UILabel * leftLb = [[UILabel alloc] init];
    leftLb.frame = CGRectMake(12, 0, 200, 35);
    leftLb.textColor = [UIColor colorWithHex:0x333333];
    leftLb.font = [UIFont systemFontOfSize:12];
    leftLb.text = @"通知被关闭，无法接收消息提醒";
    UIButton * bt = [[UIButton alloc] init];
    bt.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 80, 0, 80, 35);
    bt.titleLabel.font = [UIFont systemFontOfSize:14];
    [bt setTitle:@"前往开启" forState:UIControlStateNormal];
    [bt setTitleColor:[UIColor colorWithHex:0xff4443] forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(pushTipClickAction) forControlEvents:UIControlEventTouchUpInside];
    [pushTipView addSubview:leftLb];
    [pushTipView addSubview:bt];
    return pushTipView;
}

- (CGFloat)calculatePushTipHeight {
    
    self.pushTipHeight = 10.0;
    VGIMManager * m = [[VGIMManager alloc] init];
    dispatch_semaphore_t signal = dispatch_semaphore_create(0);
    __weak typeof(self) weakSelf = self;
//    [m pushPermissionWithPushClosure:^(CGFloat height) {
//        weakSelf.pushTipHeight = height + 10;
//        dispatch_semaphore_signal(signal);
//    }];
    dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
    return self.pushTipHeight;
}

- (void)pushTipClickAction {
    VGIMManager * m = [[VGIMManager alloc] init];
//    [m toSetting];
}

- (void)enterForeground {
    [self.tableView reloadData];
}

@end
